<style scoped>
</style>

<template>
  <div>
    <Modal
      v-model="IsModalShow"
      :title="modalFormTitle"
      :mask-closable="false"
      @on-cancel="cancel"
      width="600"
    >
      <Form
        ref="modalForm"
        :model="modalForm"
        :label-width="80"
        value="true"
        style="padding: 3px 60px"
      >
        <Form-item
          label="部门名"
          prop="name"
          :rules="{required: true, message: '必填,1-10位字符',min:1,max:10, trigger:'blur',type:'string'}"
        >
          <Input v-model="modalForm.name"></Input>
        </Form-item>
        <Form-item label="上级部门" v-if="modalForm.parentId!==0">
          <Cascader
            v-model="modalForm.cascader"
            :data="cascaderData"
            change-on-select
            :disabled="modalFormTitle == '修改部门'"
          ></Cascader>
        </Form-item>
        <Form-item
          label="推送模板"
          prop="configId"
          :rules="{required: true, message: '必选', trigger:'change', type:'number'}"
        >
          <Select v-model="modalForm.configId" placeholder="请选择" filterable>
            <Option
              v-for="item in configList"
              :value="item.value"
              :key="item.value"
            >{{ item.label }}</Option>
          </Select>
        </Form-item>
        <div>
          <!-- <Input v-model="addrSearchVal" element-id="tipinput">
            <span slot="prepend">请输入地址</span>
            <Button slot="append" icon="ios-search" @click="searchAddr"></Button>
          </Input>-->
          <div style="position:relative;margin-bottom:10px;margin-top:10px;">
            <div id="deptMap"></div>
            <!-- <div id="deptMapShade" :style="{'display':mapShadeShow?'block':'none'}"></div> -->
          </div>

          <Row>
            <Col span="10">
              <Form-item label="纬度" label-width="60">
                <Input v-model="modalForm.lat"></Input>
              </Form-item>
            </Col>
            <Col span="10">
              <Form-item label="经度" label-width="60">
                <Input v-model="modalForm.lng"></Input>
              </Form-item>
            </Col>
            <Col span="3" offset="1">
              <Button type="warning" :loading="modalForm_loading" @click="drawFence">设置区域围栏</Button>
            </Col>
          </Row>
        </div>
      </Form>
      <div slot="footer">
        <Button type="default" @click="cancel">关闭</Button>
        <Button type="primary" :loading="modalForm_loading" @click="saveForm('modalForm')">保存</Button>
      </div>
    </Modal>
  </div>
</template>

<script>
import AMap from "AMap";
import {
  saveDept,
  updateDept,
  getDeptCascader,
  configCombo
} from "@/api/system";
var mousetool = null; //画图工具
export default {
  props: {
    parentForm: {
      type: Object,
      default: function() {
        return {
          deptId: "",
          name: "",
          orderNum: "",
          parentId: "",
          parentName: "",
          cascader: ""
        };
      }
    },
    modalShow: {
      type: Boolean,
      default: true
    },
    modalFormTitle: {
      type: String,
      default: "添加部门"
    }
  },
  data() {
    return {
      IsModalShow: false,
      modalForm: {},
      modalForm_loading: false,
      cascaderData: [],
      configList: [],
      map: null,
      mousetool: null,
      mapShadeShow: false,
      addrSearchVal: "",
      polygonPoints: [] //围栏点坐标
    };
  },
  watch: {
    modalShow(curVal, oldVal) {
      this.IsModalShow = curVal;
      if (curVal) {
        this.getDeptCascader();
        let parentFormVal = JSON.parse(JSON.stringify(this.parentForm));
        if (parentFormVal.cascader) {
          parentFormVal.cascader = parentFormVal.cascader
            .split(",")
            .map(val => parseInt(val));
        } else {
          parentFormVal.cascader = [];
        }
        this.modalForm = parentFormVal;
        if (this.modalForm.lng && this.modalForm.lat) {
          this.map.clearMap();
          var _this = this;
          setTimeout(function() {
            _this.addPolygon(_this.modalForm.lng, _this.modalForm.lat);
          }, 100);
        } else {
          this.map.clearMap();
        }

        this.addrSearchVal = "";
      }
    }
  },
  created() {
    this.getConfigCombo();
  },
  mounted() {
    this.$nextTick(() => {
      this.initMap();
    });
  },
  methods: {
    cancel() {
      this.$emit("listenModalForm");
    },
    async getDeptCascader() {
      const result = await getDeptCascader();
      if (result.code == 0) {
        this.cascaderData = result.data;
      }
    },
    async getConfigCombo() {
      const result = await configCombo();
      if (result.code == 0) {
        this.configList = result.data;
      }
    },
    saveForm(name) {
      this.$refs[name].validate(async valid => {
        if (valid) {
          this.modalForm_loading = true;
          let cascader = this.modalForm.cascader.join(",");
          let parentId = this.modalForm.cascader[
            this.modalForm.cascader.length - 1
          ];
          let params = JSON.parse(JSON.stringify(this.modalForm));
          params.cascader = cascader;
          params.parentId = parentId;
          try {
            let result;
            if (this.modalFormTitle == "添加部门") {
              result = await saveDept(params);
            } else {
              result = await updateDept(params);
            }

            if (result.code == 0) {
              this.$emit("listenModalForm");
              this.$emit("refreshTableList");
            } else {
              this.$Message.error(result.msg);
            }
          } catch (err) {
            console.log(err);
            this.$Message.error("服务器异常，稍后再试");
          }
          this.modalForm_loading = false;
        } else {
          this.$Message.error("表单验证失败!");
        }
      });
    },
    initMap() {
      var _this = this;
      this.map = new AMap.Map("deptMap", {
        resizeEnable: true,
        scrollWheel: true,
        zoom: 5
      });
      this.map.plugin(["AMap.MouseTool"], function() {
        //鼠标工具插件
        mousetool = new AMap.MouseTool(_this.map);
      });
    },
    addPolygon(lng, lat) {
      this.map.clearMap();
      if (lat && lng) {
        let bound = [];
        let lats = lat.split(",");
        let lngs = lng.split(",");
        lats.forEach((item, index) => {
          bound.push([item, lngs[index]]);
        });
        let _this = this;
        var polygon = new AMap.Polygon({
          map: _this.map,
          strokeWeight: 1,
          path: bound,
          fillOpacity: 0.7,
          fillColor: "#CCF3FF",
          strokeColor: "#CC66CC"
        });
        this.map.setFitView();
      }
    },
    drawFence() {
      let _this = this;
      var mapEvent = AMap.event.addListener(mousetool, "draw", function(e) {
        let lngs = "";
        let lats = "";
        var drawObj = e.obj;
        var points = drawObj.getPath();
        let pointsLen = points.length;
        var newpoints = [];
        points.forEach((item, index) => {
          // _this.polygonPoints.push({ x: item.lat, y: item.lng });
          if (index == pointsLen - 1) {
            lngs += item.lat;
            lats += item.lng;
          } else {
            lngs += item.lat + ",";
            lats += item.lng + ",";
          }
        });
        _this.modalForm.lat = lats;
        _this.modalForm.lng = lngs;
        mousetool.close(false);
      });
      var polygonOverlays = this.map.getAllOverlays("polygon");
      this.map.clearMap();
      mousetool.polygon({
        strokeColor: "#FF33FF", //线颜色
        strokeWeight: 6, //线宽
        strokeOpacity: 0.2, //线透明度
        fillOpacity: 0.4, //填充透明度
        fillColor: "#1791fc" //填充色
      });
    }
  }
};
</script>
<style lang="less" scoped>
#deptMap {
  width: 100%;
  height: 380px;
}
#deptMapShade {
  width: 100%;
  height: 380px;
  background-color: #000000;
  position: absolute;
  opacity: 0.35;
  left: 0;
  top: 0;
  z-index: 100;
  -webkit-pointer-events: none;
  -moz-pointer-events: none;
  -ms-pointer-events: none;
  -o-pointer-events: none;
  pointer-events: none;
}
.btn {
  display: inline-block;
  font-weight: 400;
  text-align: center;
  white-space: nowrap;
  vertical-align: middle;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
  border: 1px solid transparent;
  transition: color 0.15s ease-in-out, background-color 0.15s ease-in-out,
    border-color 0.15s ease-in-out, box-shadow 0.15s ease-in-out;
  background-color: transparent;
  background-image: none;
  color: #25a5f7;
  border-color: #25a5f7;
  padding: 0.25rem 0.5rem;
  line-height: 1.5;
  border-radius: 1rem;
  -webkit-appearance: button;
  cursor: pointer;
}

.btn:hover {
  color: #fff;
  background-color: #25a5f7;
  border-color: #25a5f7;
}

.btn:hover {
  text-decoration: none;
}

.input-item {
  position: relative;
  display: -ms-flexbox;
  display: flex;
  -ms-flex-wrap: wrap;
  flex-wrap: wrap;
  -ms-flex-align: center;
  align-items: center;
  width: 100%;
  height: 3rem;
}

.input-item:last-child {
  margin-bottom: 0;
}

.input-item > select,
.input-item > input[type="text"],
.input-item > input[type="date"] {
  position: relative;
  -ms-flex: 1 1 auto;
  flex: 1 1 auto;
  width: 1%;
  margin-bottom: 0;
}

.input-item > select:not(:last-child),
.input-item > input[type="text"]:not(:last-child),
.input-item > input[type="date"]:not(:last-child) {
  border-top-right-radius: 0;
  border-bottom-right-radius: 0;
}

.input-item > select:not(:first-child),
.input-item > input[type="text"]:not(:first-child),
.input-item > input[type="date"]:not(:first-child) {
  border-top-left-radius: 0;
  border-bottom-left-radius: 0;
}

.input-item-prepend {
  margin-right: -1px;
}

.input-item-text,
input[type="text"],
input[type="date"],
select {
  height: calc(2.2rem + 2px);
}

.input-item-text {
  width: 6rem;
  text-align: justify;
  padding: 0.4rem 0.7rem;
  display: inline-block;
  text-justify: distribute-all-lines;
  /*ie6-8*/
  text-align-last: justify;
  /* ie9*/
  -moz-text-align-last: justify;
  /*ff*/
  -webkit-text-align-last: justify;
  /*chrome 20+*/
  -ms-flex-align: center;
  align-items: center;
  margin-bottom: 0;
  font-size: 1rem;
  font-weight: 400;
  line-height: 1.5;
  color: #495057;
  text-align: center;
  white-space: nowrap;
  background-color: #e9ecef;
  border: 1px solid #ced4da;
  border-radius: 0.25rem;
  border-bottom-right-radius: 0;
  border-top-right-radius: 0;
}

.input-item-text input[type="checkbox"],
.input-item-text input[type="radio"] {
  margin-top: 0;
}

.input-card {
  display: flex;
  flex-direction: column;
  min-width: 0;
  word-wrap: break-word;
  background-color: #fff;
  background-clip: border-box;
  border-radius: 0.25rem;
  width: 22rem;
  border-width: 0;
  border-radius: 0.4rem;
  box-shadow: 0 2px 6px 0 rgba(114, 124, 245, 0.5);
  position: fixed;
  bottom: 1rem;
  right: 1rem;
  -ms-flex: 1 1 auto;
  flex: 1 1 auto;
  padding: 0.75rem 1.25rem;
}

.input-text {
  line-height: 2rem;
  margin-right: 2rem;
}

.info hr {
  margin-right: 0;
  margin-left: 0;
  border-top-color: grey;
}

.info {
  padding: 0.75rem 1.25rem;
  margin-bottom: 1rem;
  border-radius: 0.25rem;
  position: fixed;
  top: 1rem;
  background-color: white;
  width: auto;
  min-width: 22rem;
  border-width: 0;
  right: 1rem;
  box-shadow: 0 2px 6px 0 rgba(114, 124, 245, 0.5);
}

.code {
  left: 1.5rem;
  right: 1.5rem;
  top: 1.5rem;
  bottom: 1.5rem;
  overflow: auto;
  margin-bottom: 0rem;
}

.code .btn {
  top: 1rem;
  position: absolute;
  right: 1rem;
}

.code .result {
  border: 1px solid rgba(0, 0, 0, 0.1);
  border-radius: 0.5rem;
  padding: 1rem;
  bottom: 1rem;
  position: absolute;
  top: 5.5rem;
  right: 1rem;
  left: 1rem;
  overflow: auto;
}

.code .status {
  color: #80adff;
  display: inline-block;
  font-size: 14px;
}

.code h4 {
  display: inline-block;
  max-width: 20rem;
  margin-right: 1rem;
  margin-bottom: 1rem;
}

select,
input[type="text"],
input[type="date"] {
  display: inline-block;
  width: 100%;
  padding: 0.375rem 1.75rem 0.375rem 0.75rem;
  line-height: 1.5;
  color: #495057;
  vertical-align: middle;
  background: #fff
    url("data:image/svg+xml;charset=utf8,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 4 5'%3E%3Cpath fill='%23343a40' d='M2 0L0 2h4zm0 5L0 3h4z'/%3E%3C/svg%3E")
    no-repeat right 0.75rem center;
  background-size: 8px 10px;
  border: 1px solid #ced4da;
  border-radius: 0.25rem;
  -webkit-appearance: none;
  -moz-appearance: none;
  appearance: none;
}

input[type="text"],
input[type="date"] {
  background: #fff;
  padding: 0.375rem 0.75rem;
}

select:focus,
input[type="text"]:focus,
input[type="date"]:focus {
  border-color: #80bdff;
  outline: 0;
  box-shadow: 0 0 0 0.1rem rgba(128, 189, 255, 0.1);
}

.btn:focus {
  outline: 0;
  box-shadow: none;
}

select:focus::-ms-value,
input[type="text"]:focus::-ms-value,
input[type="date"]:focus::-ms-value {
  color: #495057;
  background-color: #fff;
}
</style>

